package client;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Panel_connexion extends JPanel {

	JTextField chp_adr = new JTextField(10);
	JTextField chp_port = new JTextField(10);
	JButton btn_ok = new JButton();
	JButton btn_cl = new JButton();
	GridLayout gridLayout1 = new GridLayout(11,2);
	JPanel jPanel2 = new JPanel();
	JLabel messages = new JLabel();
	
	JLabel serveurs = new JLabel();
	JTextField chp_serv = new JTextField(10);
	JButton btn_sel = new JButton();
	
	JTextField chp_login = new JTextField(10);
	JTextField chp_password = new JTextField(10);
	
	JTextField chp_type = new JTextField(10);
	JTextField chp_nom = new JTextField(10);
	JButton btn_con = new JButton();
	JButton btn_ins = new JButton();
	
	private Socket s;
	
	private String adr;
	private int port;
	//serveur partie
	private String ip_ser;
	private int port_ser;
	private int port_ser_ecoute;
	private String jeton;
	
	private boolean connectionTerminee;
	private FenetreJeu fen;
	private String[] tab_s;
	
	//resultat de la connection
	private int id;
	private ArrayList<Joueur> joueurs;
	
	public Panel_connexion(FenetreJeu f)
	{
		fen = f;
		init();
	}
	
	void jButtonCONNECTER_actionPerformed(ActionEvent e) {
		//récupérer la liste des serveurs
		try
		{
			ThreadLogin th_l = new ThreadLogin(s,chp_login.getText(), chp_password.getText(), false);
			th_l.start();
			th_l.join();
			String reponse = th_l.getReponse();
			String attendu = new String("ok");
			System.out.println("Reponse Serveur principale:" +reponse);
			String[] tab_t = reponse.split("@");
			//System.out.println("Comparaison "+reponse+" et "+attendu+":"+reponse.compareTo(attendu));
			if (tab_t[1].compareTo(attendu)==0)
			{
				s.close();
		 	   ThreadConnexionPrinc th_cp = new ThreadConnexionPrinc(tab_t[2]);
		 	   th_cp.start();
		 	   th_cp.join();
		 	   tab_s = th_cp.getRes();
		 	   String msg = "<html>";
		 	   int i;
		 	   for (i=0;i<tab_s.length;i++)
		 	   {
		 		   System.out.println(i);
		 		   msg = msg + Integer.toString(i) + "->" + tab_s[i] + "<br>";
		 	   }
		 	   msg = msg + "</html>";
		 	   //ip_ser = "127.0.0.1";
		 	   //port_ser = 2332;
		 	   
		 	   //afficher la liste des serveurs
		 	   btn_ok.setEnabled(false);
		 	   btn_cl.setEnabled(false);
		 	   btn_con.setEnabled(false);
		 	   btn_ins.setEnabled(false);
		 	   chp_adr.setEnabled(false);
		 	   chp_port.setEnabled(false);
		 	   chp_login.setEnabled(false);
		 	   chp_password.setEnabled(false);
		 	   
		 	   messages.setText(msg);
		 	   chp_serv.setEnabled(true);
		 	   chp_type.setEnabled(true);
		 	   chp_nom.setEnabled(true);
		 	   btn_sel.setEnabled(true);
			}
			else
			{
				messages.setText("Probleme:" + reponse);
				System.out.println("Probleme:" + reponse);
			}
		}
		catch (IOException ex)
		{
			//
		}
		catch (InterruptedException ex)
		{
			//
		}
	}
	
	void jButtonINSCRIRE_actionPerformed(ActionEvent e) {
		try
		{
			ThreadLogin th_l = new ThreadLogin(s,chp_login.getText(), chp_password.getText(), true);
			th_l.start();
			th_l.join();
			String reponse = th_l.getReponse();
			System.out.println(reponse);
			if (reponse.equals("ok"))
			{
				messages.setText("Enregistrement effectu�");
			}
			else
			{
				messages.setText("Probleme"+reponse);
			}
		}
		catch (IOException ex)
		{
			System.out.println("Probleme IO inscription");
			ex.printStackTrace();
		}
		catch (InterruptedException ex)
		{
			System.out.println("Probleme interrupt inscription");
			ex.printStackTrace();
		}
	}
	
	void jButtonSELECT_actionPerformed(ActionEvent e) {
		//un serveur est sélectionné
		try {
			int id_serv_select = Integer.parseInt(chp_serv.getText());
			String[] info_serv = tab_s[id_serv_select].split(":");
			jeton = info_serv[6];
			ip_ser = info_serv[3];
			port_ser = Integer.parseInt(info_serv[4]);
			port_ser_ecoute = Integer.parseInt(info_serv[5]);
			//connexion
			Socket s = new Socket(InetAddress.getByName(ip_ser), port_ser);
			//ThreadEnvoiJeton th_j = new ThreadEnvoiJeton(s, jeton);
			ThreadConnection th_c = new ThreadConnection(s, jeton, chp_type.getText().charAt(0), chp_nom.getText());
			this.setEnabled(false);
			th_c.start();
			th_c.join();
			connectionTerminee = true;
			id = th_c.getId_joueur();
			joueurs = th_c.getJoueurs();
			fen.setJeu(new Jeu(new Carte(), id, joueurs));
			DatagramSocket ds = new DatagramSocket(8880);
			fen.getJeu().setAddr(InetAddress.getByName(ip_ser));
			fen.getJeu().setPort(port_ser_ecoute);
			ThreadEcouteServeurUDP th_es = new ThreadEcouteServeurUDP(ds,fen);
			fen.getJeu().setThread(th_es);
			th_es.start();
		}
		catch (IOException ex) {
			//
		}
		catch (InterruptedException ex) {
			//
		}
	}
	
	void jButtonOK_actionPerformed(ActionEvent e) {
	    //messages.setText(" ");
		try{
			System.out.println("Ok");
			port = new Integer(chp_port.getText());
			adr = chp_adr.getText();
			System.out.println(adr + ":" + port);
			InetAddress addr = InetAddress.getByName(adr);
	       
	       
			s = new Socket(addr, port); //ferm�e dans le thread connexion princ
			if (s.isConnected()) {
				chp_adr.setEnabled(false);
				chp_port.setEnabled(false);
				btn_ok.setEnabled(false);
				btn_cl.setEnabled(false);
				chp_login.setEnabled(true);
				chp_password.setEnabled(true);
				btn_con.setEnabled(true);
				btn_ins.setEnabled(true);
	       }
	       else {
	    	   throw new IOException ();
	       }
	       
	    }
	    catch(NumberFormatException nfe){
	       messages.setText("entrer un entier !");
	    }
	    catch(IOException io_e) {
	    	messages.setText("Impossible de se connecter");
	    	System.out.println("Probleme!") ;
	    }
	  }

	  void jButtonCANCEL_actionPerformed(ActionEvent e) {
	     //messages.setText(" ");
		 this.setVisible(false);
	  }
	
	public void init() {
		  btn_ok.addActionListener(new java.awt.event.ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		        jButtonOK_actionPerformed(e);
		      }
		  });
		  btn_cl.addActionListener(new java.awt.event.ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		    	  jButtonCANCEL_actionPerformed(e);
		      }
		  });
		  btn_sel.addActionListener(new java.awt.event.ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		    	  jButtonSELECT_actionPerformed(e);
		      }
		  });
		  btn_con.addActionListener(new java.awt.event.ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		    	  jButtonCONNECTER_actionPerformed(e);
		      }
		  });
		  btn_ins.addActionListener(new java.awt.event.ActionListener() {
		      public void actionPerformed(ActionEvent e) {
		    	  jButtonINSCRIRE_actionPerformed(e);
		      }
		  });
		  btn_ok.setText("Connecter");
		  btn_cl.setText("Annuler");
		  btn_sel.setText("S�lectionner");
		  btn_con.setText("Se connecter");
		  btn_ins.setText("S'enregistrer");
		  jPanel2.setLayout(gridLayout1);
		  //gridLayout1.setRows(7);
		  //gridLayout1.setColumns(2);
		  jPanel2.add(new JLabel("Adresse: "));
		  jPanel2.add(chp_adr);
		  jPanel2.add(new JLabel("Port: "));
		  jPanel2.add(chp_port);
		  jPanel2.add(btn_ok);
		  jPanel2.add(btn_cl);
		  jPanel2.add(new JLabel("Login: "));
		  jPanel2.add(chp_login);
		  jPanel2.add(new JLabel("Password: "));
		  jPanel2.add(chp_password);
		  jPanel2.add(btn_con);
		  jPanel2.add(btn_ins);
		  
		  jPanel2.add(serveurs);
		  jPanel2.add(new JLabel());
		  jPanel2.add(new JLabel("Id serveur: "));
		  jPanel2.add(chp_serv);
		  jPanel2.add(new JLabel("Type: "));
		  jPanel2.add(chp_type);
		  jPanel2.add(new JLabel("Nom: "));
		  jPanel2.add(chp_nom);
		  jPanel2.add(btn_sel);
		  //jPanel2.validate();
		  
		  //this.setLayout(new BorderLayout());
		  this.setPreferredSize(new Dimension(250, 600));
		  this.add(jPanel2);
		  this.add(messages);
		  
		  	chp_login.setEnabled(false);
			chp_password.setEnabled(false);
			btn_con.setEnabled(false);
			btn_ins.setEnabled(false);
		  
		  chp_serv.setEnabled(false);
		  chp_type.setEnabled(false);
		  chp_nom.setEnabled(false);
		  btn_sel.setEnabled(false);
	  }
	
}
